/*
 *  Copyright 2009 David Kuhn <david.s.kuhn at gmail.com>.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package com.google.code.teamtools.client.view;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.ChangeEvent;
import com.extjs.gxt.ui.client.data.ChangeListener;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.code.teamtools.client.AppEvents;
import com.google.code.teamtools.client.model.TeamMember;
import com.google.code.teamtools.client.widget.DummyEditorPanel;
import com.google.code.teamtools.client.widget.TeamMemberEditorPanel;

/**
 * 
 * @author David Kuhn <david.s.kuhn at gmail.com>
 */
public class EditorView extends View
{
	private static final String TAB_ITEM_ID_PREFIX = "x-editor-tab-item-";
	
    private LayoutContainer container;
    private TabPanel tabPanel;

    public EditorView(Controller controller)
    {
        super(controller);
    }

    @Override
    protected void handleEvent(AppEvent event)
    {
        if (event.getType() == AppEvents.NavTeam) {
            LayoutContainer wrapper = (LayoutContainer) Registry.get(AppView.CENTER_PANEL);
            wrapper.removeAll();
            wrapper.add(container);
            wrapper.layout();
            return;
        } else if (event.getType() == AppEvents.Open) {
        	onOpen(event.getData());
        }
    }

    @Override
    protected void initialize()
    {
        container = new LayoutContainer();

        BorderLayout layout = new BorderLayout();
        layout.setEnableState(false);
        container.setLayout(layout);

        tabPanel = new TabPanel();
        tabPanel.setMinTabWidth(115);
        tabPanel.setResizeTabs(true);
        tabPanel.setAnimScroll(true);
        tabPanel.setTabScroll(true);

        // TODO Create a start page that doesn't suck...
        TabItem tabItem = new TabItem("Start Page");
        tabItem.setClosable(true);
        tabItem.addText("<h1>Welcome to Team Tools!</h1>");
        tabPanel.add(tabItem);

        container.add(tabPanel, new BorderLayoutData(LayoutRegion.CENTER));
    }
    
    private TabItem createTab(String tabItemId, BeanModel model)
    {
    	/* Create the new tab which will house our editor. We give the tab a custom
    	 * ID so that on subsequent open events we can determine if we've already got 
    	 * an editor open. */
    	final TabItem tabItem = new TabItem((String) model.get("name"));
    	tabItem.setItemId(tabItemId);
    	tabItem.setClosable(true);
    	tabItem.setLayout(new FitLayout());
    	
    	/* Add a change listener to the model object so we can update the tab
    	 * title as the user edits - a nice little touch really... */
    	model.addChangeListener(new ChangeListener()
    	{
			public void modelChanged(ChangeEvent event) 
			{
				tabItem.setText((String) event.getSource().get("name"));
			}
    	});
    	
    	tabItem.add(getEditorPanel(model));
    	
    	return tabItem;
    }
    
    private ContentPanel getEditorPanel(BeanModel model)
    {
    	// Choose editor based on the type of bean passed to us.
    	Object o = model.getBean();
    	if (o instanceof TeamMember)
    		return new TeamMemberEditorPanel(model);
    	else 
    		return new DummyEditorPanel(model);
    }
     
    private void onOpen(Object data)
    {
    	/* Check that we've been sent a BeanModel object. We need the runtime
    	 * introspection offered by ModelData objects in order to bind data 
    	 * to our editor components. */
    	BeanModel model;
    	if (data instanceof BeanModel)
    		model = (BeanModel) data;
    	else
    		throw new RuntimeException("Can't edit item. Not a valid BeanModel instance!");
    	
    	// See if editor is already open, if so select it.
    	TabItem tabItem;
    	String tabItemId = TAB_ITEM_ID_PREFIX + String.valueOf(model.get("id"));
    	if ((tabItem = tabPanel.getItemByItemId(tabItemId)) != null) {
    		// No need to go any further, editor is already open so select it and finish up.
    		tabPanel.setSelection(tabItem);
    		return; 
    	}
    	
    	// Add editor to tab panel and select it.
    	TabItem newTab = createTab(tabItemId, model);
    	tabPanel.add(newTab);
    	tabPanel.setSelection(newTab);	
    }
}
